package com.slf.engine.utils;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

import com.slf.engine.common.SysContants;

public class SocketUtil {

	private static final Logger log = Logger.getLogger(SocketUtil.class);
	
	
	private static Socket client = null;
	public synchronized static Socket getInStantClient()
	{
		if(client == null)
		{
			try {
				client = new Socket(SysContants.ZJZH_IP,SysContants.ZJZH_PORT);
				if(client.isConnected())
				{
					log.log(Priority.INFO, "网络实例化成功");
					
//					SysContext.IS_BUSY = false;
					return client;
				}else{
					log.log(Priority.ERROR, "对方网络不存在，3秒钟后重新连接");
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
					}
					return getInStantClient();
				}
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				log.log(Priority.ERROR, "对方网络不存在，3秒钟后重新连接");
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
				}
				return getInStantClient();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.log(Priority.ERROR, "输出登录请求错误");
			}
		}else{
//			SysContext.IS_BUSY = true;
			if(client.isConnected())
			{
				return client;
			}else{
				try {
					client = new Socket(SysContants.ZJZH_IP,SysContants.ZJZH_PORT);
					if(client.isConnected())
					{
						log.log(Priority.INFO, "网络实例化成功");
						
//						SysContext.IS_BUSY = false;
						return client;
					}else{
						log.log(Priority.ERROR, "对方网络不存在，3秒钟后重新连接");
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
						}
						return getInStantClient();
					}
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					log.log(Priority.ERROR, "对方网络不存在，3秒钟后重新连接");
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
					}
					return getInStantClient();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.log(Priority.ERROR, "输出登录请求错误");
				}
			
			}
		}
		return null;
	}
}
